import JSEncrypt from 'jsencrypt'
import store from 'store'

import serve from '@/api/common'
import base from '@/config/base.config'
const { KEY_NAME } = base
export default /*
3. 设置获取公钥功能并且加密
*/
async function encrypts(value) {
  if (!value) {
    return
  }
  try {
    let key = store.get(KEY_NAME)
    // 使用 local要使用JSON.parse处理
    if (key === 'undefined' || !key) {
      let result = await serve.get('/keys')
      console.log(result)
      key = result.data.key
      key = key?.replace(/\. +/g, '')
      key = key?.replace(/[\r\n]/g, '')
      store.set(KEY_NAME, key)
    }
    let jsEncrypt = new JSEncrypt()
    jsEncrypt.setPublicKey(key)
    return jsEncrypt.encrypt(value)
  } catch (err) {
    console.log(err)
    return '加密失败'
  }
}
